/**
 * @ClassName KP33_BalancedBinaryTree
 * @Description: TODO
 * @Author: JCC
 * @CreateTime: 2023/10/30 12:17
 */

/**
 * 平衡二叉树
 */
public class KP33_BalancedBinaryTree {
    // 测试链接：https://leetcode.com/problems/balanced-binary-tree

    public static class TreeNode {
        public int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int val) {
            this.val = val;
        }
    }

    public static class Info {
        public boolean isBalance;
        public int height;

        public Info(boolean isBalance, int height) {
            this.isBalance = isBalance;
            this.height = height;
        }
    }

    public boolean isBalanced(TreeNode root) {
        return isBalancedTree(root).isBalance;
    }

    public Info isBalancedTree(TreeNode root) {
        if (root == null) {
            return new Info(true, 0);
        }
        Info leftChild = isBalancedTree(root.left);
        Info rightChild = isBalancedTree(root.right);
        int height = Math.max(leftChild.height, rightChild.height) + 1;
        boolean isBalance = leftChild.isBalance && rightChild.isBalance && Math.abs(leftChild.height - rightChild.height) < 1;
        return new Info(isBalance, height);
    }

}
